import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/config/config.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

class AuthorizedLoginPage extends StatefulWidget {
  const AuthorizedLoginPage({super.key});

  @override
  State<AuthorizedLoginPage> createState() => _AuthorizedLoginPageState();
}

class AuthorizedData {
  String ticket = '';
  String key = '';
  AuthorizedData(this.ticket, this.key);

  Map<String, dynamic> toJson() {
    return {'ticket': ticket, 'key': key};
  }
}

class _AuthorizedLoginPageState extends State<AuthorizedLoginPage> {
  bool loading = true;
  bool succeed = false;
  bool submiting = false;
  String qrcodeUrl = '';
  AuthorizedData data = AuthorizedData('', '');
  Map<String, dynamic> content = {};
  @override
  void initState() {
    qrcodeUrl = Get.parameters['qrcode'].toString();

    super.initState();
  }

  @override
  void dispose() {
    cancel();
    super.dispose();
  }

  resolve(context) async {
    Uri uri = Uri.parse(qrcodeUrl);
    if (uri.origin.replaceFirst('http://', 'https://') != Config.server) {
      await Ui.alert('二维码不合法');
      App.back(context);
      return;
    }
    List<String> params = uri.path.split('/');
    if (params.length >= 4) {
      data = AuthorizedData(params[3], params[4]);
      var res = await Http.instance.post(
        '/plugin/user_authorized/user/resolve',
        data: data.toJson(),
      );
      setState(() {
        loading = false;
      });
      if (res.code == 0) {
        await Ui.alert(res.msg);
        return App.back(context);
      }

      setState(() {
        content = res.data;
      });
    }
  }

  cancel() async {
    if (!succeed) {
      Http.instance.post(
        '/plugin/user_authorized/user/cancel',
        data: data.toJson(),
      );
    }
  }

  confirm(context) async {
    setState(() {
      submiting = true;
    });
    var res = await Http.instance.post(
      '/plugin/user_authorized/user/confirm',
      data: data.toJson(),
    );
    setState(() {
      submiting = false;
    });
    succeed = res.code == 1;
    if (succeed) {
      App.back(context);
    }
    Ui.toast(res.msg);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(content['title'] ?? '扫码授权'),
      ),
      body: UiLifeCycle(
        onRouteDone: () {
          resolve(context);
        },
        child: SingleChildScrollView(
          child: Column(
            children: [
              const SizedBox(height: 100),
              Center(
                child: Icon(
                  UiIcons.desktop,
                  color: UiTheme.primary.withOpacity(0.5),
                  size: 150,
                ),
              ),
              const SizedBox(height: 10),
              if (loading) const CupertinoActivityIndicator(),
              Padding(
                padding: const EdgeInsets.only(top: 10.0),
                child: Text(
                  content['name'] ?? '',
                  style: const TextStyle(
                    fontSize: 16,
                  ),
                ),
              ),
              if (Ui.isNotEmpty(content['intro']))
                Padding(
                  padding: const EdgeInsets.only(top: 10.0),
                  child: Opacity(
                    opacity: 0.6,
                    child: Text(
                      content['intro'] ?? '',
                    ),
                  ),
                ),
              if (Ui.isNotEmpty(content['befrom']))
                Padding(
                  padding: const EdgeInsets.only(top: 10.0),
                  child: Opacity(
                    opacity: 0.6,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Icon(Icons.location_pin, size: 14),
                        const SizedBox(width: 3),
                        Text(
                          content['befrom'] ?? '',
                        ),
                      ],
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: content['id'] == null
          ? null
          : SafeArea(
              bottom: true,
              minimum: const EdgeInsets.only(bottom: 20),
              child: IntrinsicHeight(
                child: SizedBox(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: UiTheme.spacingXX),
                    child: Column(
                      children: [
                        SizedBox(
                          width: double.infinity,
                          child: UiButton(
                            onPressed: () {
                              confirm(context);
                            },
                            loading: submiting,
                            disabled: succeed || submiting,
                            borderRadius: BorderRadius.circular(20),
                            child: Text(content['confirmText'] ?? '确定'),
                          ),
                        ),
                        const SizedBox(height: 10),
                        SizedBox(
                          width: double.infinity,
                          child: UiButton(
                            onPressed: () {
                              App.back(context);
                            },
                            borderRadius: BorderRadius.circular(20),
                            backgroundColor:
                                Theme.of(context).scaffoldBackgroundColor,
                            child: Text(
                              content['cancelText'] ?? '取消',
                              style: TextStyle(
                                color: UiTheme(context)
                                    .matchColor(Colors.black54, Colors.white70),
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(height: 10),
                      ],
                    ),
                  ),
                ),
              )),
    );
  }
}
